package com.zxm.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.zxm.ssm.Aspect.Interfaces.Permission;
import com.zxm.ssm.entity.Inform;
import com.zxm.ssm.entity.Product;
import com.zxm.ssm.service.InformService;
import com.zxm.ssm.service.ProductService;
import com.zxm.ssm.utils.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


@Controller
public class ProductController {
    @Autowired
    private ProductService productService;

    @Autowired
    private InformService informService;

    @Permission
    @RequestMapping("/product/list")
    public String list(Model model,
                       @RequestParam(required = false, defaultValue = "1") int pageNum,
                       @RequestParam(required = false, defaultValue = "3") int pageSize) {
        PageInfo<Product> pageInfo = productService.findAllProducts(pageNum, pageSize);

        model.addAttribute("pageInfo", pageInfo);
        return "product/list";
    }

    @Permission
    @RequestMapping("/product/del")
    public String del(Model model, int id) {
        int ret = productService.deleteProduct(id);
        model.addAttribute("ret", ret);
        return "redirect:/product/list";
    }

    /**
     * 添加商品
     */
    @Permission
    @GetMapping("/product/add")
    public String toAdd(Product product, Model model) {
        return "product/add";
    }

    @Permission
    @PostMapping("/product/add")
    public String doAdd(Product product, BindingResult result, MultipartFile photox, Model model, HttpServletRequest request) throws IOException {
//        if (!photox.isEmpty()) {
//            System.out.println("doAdd方法");
//            String realPath = request.getRealPath("/upload/");
//            System.out.println("===================" + photox);
//            String ext = photox.getOriginalFilename().substring(photox.getOriginalFilename().lastIndexOf("."));
//            String newFileName = UUID.randomUUID() + ext;
//            photox.transferTo(new File(realPath + newFileName));
//            System.out.println(realPath);
//            product.setPicture(newFileName);
//        }

        String uploadUrl = null;
        OssUtil ossUtil = new OssUtil();
        try {
            if (photox != null) {
                String filename = photox.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(photox.getBytes());
                    os.close();
                    photox.transferTo(newFile);
                    //上传到OSS
                    uploadUrl = ossUtil.upload(newFile);
                    product.setPicture(ossUtil.getUrl(uploadUrl));
                    newFile.delete();//删除保存在本地的文件，若需要保存在本地则注释掉
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        int ret = productService.insertProduct(product);
        if (ret > 0) {
            /*使用绝对路径*/
            return "redirect:/product/list";
        }
        return "product/add";
    }

    @Permission
    @GetMapping("/product/edit")
    public String toEdit(Model model, Product product, int id) {
        product = productService.findProductById(id);
        model.addAttribute("product", product);
        return "product/edit";
    }

    @Permission
    @PostMapping("/product/edit")
    public String doEdit(Product product, BindingResult result, MultipartFile photox, Model model, HttpServletRequest request) throws IOException, IOException {
//        if(result.hasErrors()){
//            List<Type> types = bookService.findAllTypes();
//            model.addAttribute("types",types);
//            return "book/edit";
//        }
//        if (!photox.isEmpty()) {
//            String realPath = request.getRealPath("/upload/");
//            System.out.println("===================" + photox);
//            String ext = photox.getOriginalFilename().substring(photox.getOriginalFilename().lastIndexOf("."));
//            String newFileName = UUID.randomUUID() + ext;
//            photox.transferTo(new File(realPath + newFileName));
//            System.out.println(realPath);
//            product.setPicture(newFileName);
//        }
        String uploadUrl = null;
        OssUtil ossUtil = new OssUtil();
        try {
            if (photox != null) {
                String filename = photox.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(photox.getBytes());
                    os.close();
                    photox.transferTo(newFile);
                    //上传到OSS
                    uploadUrl = ossUtil.upload(newFile);
                    product.setPicture(ossUtil.getUrl(uploadUrl));
                    newFile.delete();//删除保存在本地的文件，若需要保存在本地则注释掉
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        int ret = productService.updateProduct(product);
        if (ret > 0) {
            /*使用绝对路径*/
            return "redirect:/product/list";
        }
        return "product/edit";
    }


    /*舒龙*/

    @RequestMapping("/fount/fount_product_list")
    public String fountProductList(Model model,
                                   @RequestParam(required = false, defaultValue = "1") int pagNum,
                                   @RequestParam(required = false, defaultValue = "4") int pagSize) {

        PageInfo<Product> pageInfo = productService.findAllProduct(pagNum, pagSize);
        model.addAttribute("pageInfo", pageInfo);

        return "fount/fount_product_list";
    }

    @RequestMapping("/fount/fount_inform_list")
    public String fountInformList(Model model,
                                  @RequestParam(required = false, defaultValue = "1") int pagNum,
                                  @RequestParam(required = false, defaultValue = "4") int pagSize) {
        PageInfo<Inform> pageInfo = informService.findAllInform(pagNum, pagSize);
        model.addAttribute("pageInfo", pageInfo);

        System.out.println("++++++++++++++++++++");
        System.out.println(pageInfo.toString());
        return "fount/fount_inform_list";
    }

    @RequestMapping("/fount/fount_details_list")
    public String fountDetailsList(Model model, int id) {

        System.out.println("id=" + id);
        Product product = productService.findProductById(id);
        model.addAttribute("product", product);
        return "fount/fount_details_list";
    }

    @RequestMapping("system_maintenance")
    public String buy() {
        return "fount/system_maintenance";
    }
}
